package com.mydemo.thread;

import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

/**
 * <p></p >
 *
 * @author liming1
 * @version $Id: ConditionThread, v1.0 2019-09-23 11:23 liming1 Exp $
 */
public class ConditionThread {

    Lock lock = new ReentrantLock();
    private Condition control = lock.newCondition();

    public static void main(String[] args) {
        ConditionThread conditionThread = new ConditionThread();
        Constomer constomer = conditionThread.new Constomer();
        Producer producer = conditionThread.new Producer();
        new Thread(constomer).start();
        new Thread(producer).start();
    }


    class Constomer implements Runnable {
        @Override
        public void run() {
            lock.lock();
            System.out.println("开始取数据");
            try {
                control.await();
                System.out.println("已取到数据");
            } catch (InterruptedException e) {
                e.printStackTrace();
            } finally {
                lock.unlock();
            }
        }
    }


    class Producer implements Runnable {
        @Override
        public void run() {
            try {
                lock.lock();
                System.out.println("开始生产数据");
                control.signal();
                System.out.println("已生产数据");
            } finally {
                lock.unlock();
            }
        }
    }

}
